const app = getApp();
import { backMini } from "../../../utils/outData";
Page({
  data: {
    orderId: '',
    payTotal: '',
    payTime: '',
    orderFrom: ''
  },
  onLoad(options) {
    my.removeStorage({ key: 'orderId' });
    const { orderId, payTotal, payTime } = options;
    const { orderFrom } = app.globalData
    this.setData({
      orderId,
      payTotal, payTime, 
      orderFrom: orderFrom || 'search' 
    });
    my.setNavigationBar({ title: '支付' });
  },
  checkOrder() {
    const { orderId, orderFrom } = this.data;
    if(orderFrom == 'anba'){
      backMini('checkIsvOrderpay', orderId)
    } else {
      // my.reLaunch({
      //   url: '/pages/user/orderpay/orderpay?id=' + orderId
      // })
      my.showLoading({
        content:'合同生成中...',
        success:(res=>{
          this.createContractMe(orderId);
        })
      })
      setTimeout(() => {
        my.hideLoading()
      }, 3000);
    }
  },
  createContractMe(orderId,pay_type=1){
    const env = 'prod'
    if(pay_type == 2){
    // const that = this
    // createContract(orderId).then(res => {
    //   if (res.flowId) {
    //     my.hideLoading({ page: this });
    //     my.setStorage({ key: 'hasCreateSign', data: true });
    //     const { flowId, signerId } = res
    //     my.navigateTo({
    //       url: `plugin://esign/esign?env=${env}&flowId=${flowId}&signerId=${signerId}`,
    //     })
    //   }
    // })
    const that = this
    createAntchain(orderId).then(res => {
      console.log('res', res)
      my.showLoading({ content: '正在跳转合同...' });
      function getSignUrl(aliSchema) {
        if (!aliSchema) { return '' }
        const querys = aliSchema.split('?')[1].split('&');
        const signUrlKeyValue = querys.find((item) => item.includes('query=')).replace('query=', '');
        const encodedSignUrl = decodeURIComponent(signUrlKeyValue).replace('signUrl=', '');
        return encodedSignUrl
      }
      const signUrl = getSignUrl(res.sign_url);
      my.navigateToMiniProgram({
        appId: '2021001152620480',
        path: `pages/signH5/index?signUrl=${signUrl}`,
        success: (res) => {
          console.log(JSON.stringify(res))
          my.hideLoading({
            page: that,
          });
        },
        fail: (res) => {
          my.hideLoading({
            page: that,
          });
          console.log(JSON.stringify(res))
        }
      });
    })
      }else if(pay_type == 1){
        my.navigateTo({
          url: '../chainContract/chainContract?orderId=' + orderId
        })
      }
  },
  returnHome() {
    const { orderFrom } = this.data;
    if(orderFrom == 'anba'){
      backMini('checkIsvHome')
    } else {
      my.switchTab({ url: '../../../pages/index/index' });
    }
  }
});
